package com.qiantu.phone.ui.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.hjq.base.BaseDialog;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.utils.SPUtils;
import com.qiantu.phone.widget.EditTextLayout;
import com.lxj.xpopup.XPopup;

import java.util.List;

/**
 * 配置无线网络
 * time   : 2021/12/22
 */
public class SetNetWorkWifiActivity extends AppActivity {

    public static final String WIFI_SSID = "wifi_ssid";
    public static final String WIFI_PASSWORD = "wifi_password";

    protected TextView tvWifiName;
    protected EditTextLayout editWifiPassword;
    protected TextView btnNext;
    protected View btnSelectWifi;
    private WifiManager wifiManager;
    private IntentFilter mWifiConnectIntentFilter;
    private BroadcastReceiver mWifiConnectBroadcastReceiver;
    private volatile String ssid = "";//连接的wifi
    private final Object object = new Object();
    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;
    private boolean hasWiredAdd;
    private XXPermissions xxPermissions;
    private boolean hasRequestPermissionsResult;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_set_wifi;
    }

    @Override
    protected void initView() {
        tvWifiName = findViewById(R.id.tv_wifi_name);
        btnSelectWifi = findViewById(R.id.btn_select_wifi);
        editWifiPassword = findViewById(R.id.edit_wifi_password);
        btnNext = findViewById(R.id.btn_next);
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        initBroadcastReceiver();
        String historyPwd = SPUtils.getInstance().getString(tvWifiName.getText().toString());
        if (!historyPwd.isEmpty()) {
            editWifiPassword.setText(historyPwd);
        }
        editWifiPassword.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editWifiPassword.getText().length() != 0 && tvWifiName.getText().length() != 0) {
                    if (!getResources().getString(R.string.no_wifi_state).equals(tvWifiName.getText())
                            && !TextUtils.isEmpty(tvWifiName.getText()) && wifiManager.isWifiEnabled()) {
                        btnNext.setEnabled(true);
                    }
                } else {
                    btnNext.setEnabled(false);
                }
            }
        });
        tvWifiName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editWifiPassword.getText().length() != 0 && tvWifiName.getText().length() != 0) {
                    if (!getResources().getString(R.string.no_wifi_state).equals(tvWifiName.getText())
                            && !TextUtils.isEmpty(tvWifiName.getText()) && wifiManager.isWifiEnabled()) {
                        btnNext.setEnabled(true);
                    }
                } else {
                    btnNext.setEnabled(false);
                }
            }
        });
        setOnClickListener(btnSelectWifi, btnNext);
        //是否需要有线添加
        hasWiredAdd = getIntent().getBooleanExtra("hasWiredAdd", false);
        if (!hasWiredAdd) {
            setRightTitle(null);
        }
        registerReceiver(mWifiConnectBroadcastReceiver, mWifiConnectIntentFilter);
    }

    @Override
    public void onRightClick(View view) {
        showBottomEditDialog();
    }

    private BottomEditDialog mBottomEditDialog;
    private void showBottomEditDialog() {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setOnConfirmDismiss(false);
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    String deviceSn = mBottomEditDialog.getText();
                    if(TextUtils.isEmpty(deviceSn)){
                        toast(R.string.please_enter_serial_number);
                        return;
                    }
                    mBottomEditDialog.dismiss();
                    //有线添加
                    Intent intent = new Intent(getContext(), AddDevice2Activity.class);
                    intent.putExtra("productLinkType", AddDevice1Activity.TYPE_WIRED_ADD);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                    finish();
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        mBottomEditDialog.setLabel(getString(R.string.serial_number_add));
        mBottomEditDialog.setBtnText(getString(R.string.add));
        mBottomEditDialog.setHint(getString(R.string.please_enter_serial_number));
        mBottomEditDialog.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!hasRequestPermissionsResult && (!XXPermissions.isGranted(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                || !XXPermissions.isGranted(this, Manifest.permission.ACCESS_FINE_LOCATION))) {
            if(AppApplication.isHuawei() ){
                showConfirmHintDialog("App需要使用定位功能才能获取您手机当前得Wi-Fi，从而通过手机给TLC1发送网络信息。如若已拒绝，再使用本功能前请先前往手机设置中将本应用的定位权限改为允许。");
            }else{
                requestPermissions();
            }
        }
        hasRequestPermissionsResult = false;
    }

    private BaseDialog mConfirmHintDialog1;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder1;

    private void showConfirmHintDialog(String text) {
        if (mConfirmHintDialog1 == null) {
            mConfirmHintDialogBuilder1 = new ConfirmHintDialog.Builder(getActivity())
                    .setRightBtnText(getString(R.string.ok))
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                            finish();
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            requestPermissions();
                        }
                    });
            mConfirmHintDialog1 = mConfirmHintDialogBuilder1.create();
        }
        mConfirmHintDialogBuilder1.setCancelable(false);
//        mConfirmHintDialogBuilder.setCanceledOnTouchOutside(false);
        mConfirmHintDialogBuilder1.setContent(text);
        mConfirmHintDialog1.show();
    }

    private void requestPermissions() {
        if (xxPermissions == null) {
            xxPermissions = XXPermissions.with(getActivity());
        }
        xxPermissions.permission(Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        hasRequestPermissionsResult = true;
                        if (all) {
                            if (isLocationEnabled()) {
                                getConnectWifiSSID();
                            } else {
                                //位置没打开时，没获取到wifi时候提示
                                if (TextUtils.isEmpty(tvWifiName.getText())) {
                                    ToastUtils.show("获取当前连接WiFi失败，请开启位置信息");
                                }
                            }
                        } else {
                            ToastUtils.show("获取当前连接WiFi失败，请允许定位权限");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        hasRequestPermissionsResult = true;
                        ToastUtils.show("获取当前连接WiFi失败，请允许定位权限");
                        if (never) {
                            showConfirmHintDialog(R.string.go_to_open_location_permission);
                        }
                    }
                });
    }

    private boolean isLocationEnabled() {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }

    /**
     * 获取连接wifi的ssid
     *
     * @return
     */
    private void getConnectWifiSSID() {
        if (wifiManager.isWifiEnabled()) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            String ssid = wifiInfo.getSSID().replaceAll("\"", "");
            if (TextUtils.isEmpty(ssid)) {
                int networkId = wifiInfo.getNetworkId();
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
                for (WifiConfiguration wifiConfiguration : configuredNetworks) {
                    if (wifiConfiguration.networkId == networkId) {
                        ssid = wifiConfiguration.SSID;
                        break;
                    }
                }
            }
            if (!"<unknown ssid>".equals(ssid)) {
                tvWifiName.setText(ssid);
                String historyPwd = SPUtils.getInstance().getString(tvWifiName.getText().toString());
                if (!TextUtils.isEmpty(historyPwd)) {
                    editWifiPassword.setText(historyPwd);
                } else {
                    editWifiPassword.setText(null);
                }
            }
        }
    }

    private void initBroadcastReceiver() {
        //wifi 状态变化接收广播
        mWifiConnectIntentFilter = new IntentFilter();
        mWifiConnectIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        mWifiConnectIntentFilter.addAction(WifiManager.ACTION_PICK_WIFI_NETWORK);
        mWifiConnectIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        mWifiConnectIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        mWifiConnectIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        mWifiConnectIntentFilter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
        mWifiConnectBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(action)) {
                    getConnectWifiSSID();
                } else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
                    int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
                    if (wifiState != WifiManager.WIFI_STATE_ENABLED) {
                        tvWifiName.setText(getResources().getString(R.string.no_wifi_state));
                        editWifiPassword.setText(null);
                    }
                } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
                    NetworkInfo.DetailedState state = ((NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO)).getDetailedState();
                    if (state == NetworkInfo.DetailedState.CONNECTED) {//已连接
                        getConnectWifiSSID();
                    }
                }
            }
        };
    }

    @Override
    protected void initData() {

    }

    public void toWifiSetting() {
        Intent i = new Intent(Settings.ACTION_WIFI_SETTINGS);
        startActivity(i);
    }

    private void showConfirmHintDialog(int res) {
        if (mConfirmHintDialog == null) {
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getActivity())
                    .setRightBtnText(getString(R.string.goto_setting))
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            gotoAppSettings();
                        }
                    });
//            mConfirmHintDialogBuilder.setAutoDismiss(false);
//            mConfirmHintDialogBuilder.setCanceledOnTouchOutside(false);
//            mConfirmHintDialogBuilder.setCancelable(false);
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
        mConfirmHintDialogBuilder.setContent(res);
        mConfirmHintDialog.show();
    }

    public void gotoAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getContext().getPackageName()));
        getContext().startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_select_wifi:
                toWifiSetting();
                break;
            case R.id.btn_next:
                if(xxPermissions == null){
                    xxPermissions = XXPermissions.with(this);
                }
                xxPermissions.permission(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onGranted(List<String> permissions, boolean all) {
                                if (all) {
                                    if (isLocationEnabled()) {
                                        next();
                                    } else {
                                        //位置没打开时，没获取到wifi时候提示
                                        if (TextUtils.isEmpty(tvWifiName.getText())) {
                                            ToastUtils.show("无线配网需要开启位置信息");
                                        }
                                    }
                                } else {
                                    ToastUtils.show("无线配网需要定位权限");
                                }
                            }

                            @Override
                            public void onDenied(List<String> permissions, boolean never) {
                                ToastUtils.show("无线配网需要定位权限");
                                if (never) {
                                    showConfirmHintDialog(R.string.go_to_open_location_permission);
                                }
                            }

                        });
                break;
        }
    }

    private void next() {
        SPUtils.getInstance().put(tvWifiName.getText().toString(), editWifiPassword.getText().toString());
        Intent intent = new Intent(this, AddDevice3Activity.class);
        intent.putExtra(WIFI_SSID, tvWifiName.getText().toString());
        intent.putExtra(WIFI_PASSWORD, editWifiPassword.getText().toString());
        //if_anewWiFi布尔值作为重联网判断标识
        if (!hasWiredAdd){
            intent.putExtra("if_anewWiFi",true);
        }
        intent.putExtra("productLinkType", AddDevice1Activity.TYPE_WIFI_ADD);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mWifiConnectBroadcastReceiver);
    }
}
